﻿using RimWorld;
using Verse;
using System.Collections.Generic;
using System.Linq;
using System;

namespace RimZombieGirl
{
    public class GenStep_CursedGrave : GenStep
    {
        public ThingDef graveDef;           // 要生成的坟墓Def
        public IntRange count = new IntRange(3, 6); // 随机生成数量
        public int minEdgeDistance = 10;    // 距离边缘的最小距离

        public override int SeedPart => 20250918;

        public override void Generate(Map map, GenStepParams parms)
        {
            if (graveDef == null)
            {
                Log.Error("[GenStep_CursedGrave] graveDef 未设置");
                return;
            }

            int spawnCount = count.RandomInRange;
            List<IntVec3> usedCells = new List<IntVec3>();

            for (int i = 0; i < spawnCount; i++)
            {
                if (TryFindRandomNotEdgeCellWith(minEdgeDistance, c =>
                    c.Standable(map) &&
                    !c.Fogged(map) &&
                    c.GetFirstBuilding(map) == null &&
                    map.zoneManager.ZoneAt(c) == null &&
                    !usedCells.Contains(c), map, out IntVec3 cell))
                {
                    Building grave = (Building)ThingMaker.MakeThing(graveDef);
                    GenSpawn.Spawn(grave, cell, map, WipeMode.Vanish);
                    usedCells.Add(cell);
                }
            }
        }

        public static bool TryFindRandomNotEdgeCellWith(int minEdgeDistance, Predicate<IntVec3> validator, Map map, out IntVec3 result)
        {
            for (int i = 0; i < 1000; i++)
            {
                result = CellFinder.RandomNotEdgeCell(minEdgeDistance, map);
                if (result.IsValid && validator(result))
                {
                    return true;
                }
            }

            result = IntVec3.Invalid;
            return false;
        }
    }
}
